<template>
  <VPage>
    <PageWrap>
      <template #form>
        <div class="w-[100%]">
          <VForm
            ref="formRef"
            :fieldList="fieldList"
            :options="formOption"
            @submit="handleSearch"
            @reset="handleSearch"
            :model="model"
            :originOption="optionsDataAll"
          />
          <ActionBar :actions="actions" />
        </div>
      </template>
      <Table
        ref="tableRef"
        :params="params"
        @status="handleStatusReq"
        :channelId="channelId"
        @edit="handleEdit"
        v-model:deliverMode="deliverMode"
        v-model:billingType="billingType"
      />
    </PageWrap>
    <add
      v-model="visible"
      :id="id"
      :channelId="channelId"
      :deliverMode="deliverMode"
      :billingType="billingType"
      :options="optionsDataAll"
      :currency="channel_currency"
      :type="type"
      @close="
        id = '';
        type = '';
      "
      @refresh="handleRefresh"
    />
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <SetArea
      v-model="setAreaVisible"
      :ids="etAreaIds"
      @close="etAreaIds = []"
      @refresh="handleRefresh"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import PageWrap from "@/components/PageWrap/index.vue";
import VForm from "@/components/Form/index.vue";
import ActionBar from "@/components/ActionBar/index.vue";
import DerivedCenter from "@/components/DerivedCenter";
import { config_name } from "@/config/export.js";
import Table from "./components/Table/index.vue";
import add from "./add/index.vue";
import { statusMap } from "@/data";
import { getLogisticsAttr } from "@/api/public.js";
import {
  statusTransportCost,
  deleteTransportCost,
  transportCostFile,
} from "./api";
import { overallOptions } from "@/api/public";
import SetArea from "./components/SetArea/idnex.vue";
import { useEnumSelect } from "@/hooks/useEnumSelect.js";
const emits = defineEmits(["search"]);

const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const id = ref();
const tableRef = ref();
const visible = ref(false);
const params = ref({});
const model = ref({});
const deliverMode = ref();
const billingType = ref();
const optionsData = ref({});
const channelId = ref();
const { options: optionsData1 } = useEnumSelect({
  params: ["surcharge_rule_type", "channel_calc_fuel_mode", "ctc_ests_state"],
});
const optionsDataAll = computed(() =>
  Object.assign({}, optionsData.value, optionsData1.value, {
    symbol: [
      { label: "<", value: 3 },
      { label: "<=", value: 4 },
    ],
  })
);
const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "channel_name",
    type: "select",
    origin: "map.channel",
    ...publicStyle,
    options: {
      placeholder: "渠道名称",
      labelKey: "channel_name",
      valueKey: "channel_name",
    },
    itemProps: {
      onChange: (e) => handleChannel(e),
    },
  },
  {
    field: "goods_attrs",
    type: "select",
    multiple: true,
    originField: "logisticsAttributes",
    options: {
      placeholder: "货物类型",
    },
    ...publicStyle,
  },
  { field: "shipping_address", placeholder: "始发站", ...publicStyle },
  {
    field: "arrival_address",
    type: "select",
    origin: "map.country",
    multiple: true,
    options: {
      placeholder: "目的地",
      valueKey: "country_name",
      labelKey: "country_name",
    },
  },
  {
    field: "file_md5",
    type: "select",
    originField: "file_name_data",
    options: {
      placeholder: "运价文件名",
      valueKey: "file_md5",
      labelKey: "name",
    },
    ...publicStyle,
  },
  {
    field: "status",
    placeholder: "状态",
    type: "select",
    options: {
      placeholder: "状态",
      data: statusMap,
    },
    ...publicStyle,
  },
  {
    field: "ests_state",
    placeholder: "生效状态",
    type: "select",
    originField: "ctc_ests_state",
    options: {
      placeholder: "状态",
    },
    ...publicStyle,
  },
  {
    field: "time",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "120px" },
    select: [
      { label: "版本时间", value: "v_times" },
      { label: "系统生效时间", value: "sys_ests_times" },
    ],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
];

const formOption = {
  inline: true,
  option: true,
  showResetButton: true,
};
const channel_Data = ref([]);
const channel_currency = ref();
onMounted(async () => {
  await getOptions();
  await getChannel();
  const { id, currency } = route.query;
  channel_currency.value = currency;
  channelId.value = id;
  await getCostFile(id);
  let channel = channel_Data.value?.mapChannel?.find(
    (n) => n.id == id
  )?.channel_name;
  model.value.channel_name = [channel];
});

const getChannel = async () => {
  try {
    const { data } = await overallOptions({
      params: ["map.channel"],
      option: "new",
    });
    channel_Data.value = data;
  } catch (error) {}
};
const getOptions = async () => {
  try {
    const { data: logisticsAttributes } = await getLogisticsAttr();
    if (logisticsAttributes) {
      optionsData.value = {
        logisticsAttributes,
      };
    }
  } catch (e) {
    console.error(e);
  }
};
const getCostFile = async (channel_id) => {
  try {
    const { data } = await transportCostFile({ channel_id });
    console.log(data);
    optionsData.value.file_name_data = data
      ?.filter((n) => n.file_name)
      ?.map((n) => ({ name: n.file_name, file_md5: n.file_md5 }));
    console.log(optionsData.value.file_name_data);
  } catch (e) {
    console.error(e);
  }
};
const getSelectRows = () => {
  const rows = tableRef.value?.tableRef.getCheckboxRecords();
  if (!rows?.length) {
    ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    });
    return [];
  }
  return rows;
};

const handleStatus = (status) => {
  const rows = getSelectRows();
  if (!rows.length) return;
  const id = rows.map((n) => n.id);
  handleStatusReq(id, status);
};

const handleStatusReq = (id, flag) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{flag ? "启用" : "禁用"}选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await statusTransportCost({ id, status: flag ? 1 : 0 });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          handleRefresh();
        }
      } else {
        done();
      }
    },
  });
};

const handleDelete = () => {
  const rows = getSelectRows();
  if (!rows.length) return;
  const id = rows.map((n) => n.id);
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await deleteTransportCost({ id });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          handleRefresh();
        }
      } else {
        done();
      }
    },
  });
};

//批量设置不可发区域
const setAreaVisible = ref(false);
const etAreaIds = ref([]);
const handleSetArea = () => {
  const rows = getSelectRows();
  if (!rows.length) return;
  const ids = rows.map((n) => n.id);
  etAreaIds.value = ids;
  setAreaVisible.value = true;
};
const type = ref();
const handleEdit = (_id) => {
  id.value = _id;
  visible.value = true;
};
const handleAdd = () => {
  visible.value = true;
  type.value = "add";
};
const handleRefresh = () => {
  nextTick(() => {
    tableRef.value?.tableRef.commitProxy("reload");
  });
};
const handleSearch = (values) => {
  const { time } = values || {};
  params.value = {
    ...values,
    [time?.key]: time?.value,
    time: undefined,
  };
  handleRefresh();
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = () => {
  DerivedCenterRef.value?.open({
    tag_name: config_name["logistics_settings"]["channel_cost"],
    condition: { ...params.value, channel_id: channelId.value },
  });
};
const formRef = ref();
const handleChannel = async (e) => {
  let item = channel_Data.value.mapChannel.find((n) => n.channel_name == e);
  router.push({
    path: `/logistics-settings/channel/transport-cost`,
    query: { id: item.id, currency: item?.currency || "CNY" },
  });
  channelId.value = item.id;
  channel_currency.value = item.currency;
  let data = await formRef.value?.getFormValues();
  data.channel_name = e;
  data.file_md5 = "";
  model.value = data;
  await getCostFile(item.id);
  nextTick(() => {
    handleSearch(data);
  });
};

const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: handleAdd,
  },
  { label: "删除", icon: "icon-del text-[#E50113]", fn: handleDelete },
  {
    label: "启用",
    icon: "state_finish_line",
    fn: () => handleStatus(true),
  },
  {
    label: "禁用",
    icon: "state_disabled",
    fn: () => handleStatus(false),
  },
  {
    label: "批量设置不可发区域",
    fn: handleSetArea,
  },
  { label: "导出", right: true, dkicon: "icon-Upload", fn: handleExport },
];
</script>
<style lang="scss" scoped>
:deep(.page-wrap__content) {
  padding: 0 10px;
}
</style>
